package com.yc.services;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.bean.OrderItems;
import com.yc.mapper.OrderItemsMapper;
import com.yc.mapper.ProductMapper;
import com.yc.web.DTO.OrderItemsDTO;
import com.yc.web.DTO.ProductDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderItemsServiceImpl implements OrderItemsService {

    private final OrderItemsMapper orderItemsMapper;
    private final ProductService productService;

    // 使用构造器注入
    public OrderItemsServiceImpl(OrderItemsMapper orderItemsMapper, ProductService productService) {
        this.orderItemsMapper = orderItemsMapper;
        this.productService = productService;
    }

    /**
     * 根据订单ID查询订单项
     * @param orderId 订单ID
     * @return
     */
    @Override
    public List<OrderItemsDTO> getItemsByOrderId(Long orderId) {
        // 1. 构建查询条件 - 查询指定orderId的所有订单项
        LambdaQueryWrapper<OrderItems> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItems::getOrderId, orderId);

        // 2. 执行查询
        List<OrderItems> orderItems = orderItemsMapper.selectList(queryWrapper);

        List<OrderItemsDTO> orderItemsDTOS = orderItems.stream().map(item -> {
            OrderItemsDTO dto = new OrderItemsDTO();
            // 使用BeanUtils复制属性
            BeanUtils.copyProperties(item, dto);
            return dto;
        }).collect(Collectors.toList());

        // 3. 关联查询商品信息
        orderItemsDTOS.forEach(item -> {
            ProductDTO productDTO = productService.getProductById(item.getProductId());
            item.setProductDTO(productDTO);
        });

        return orderItemsDTOS;
//        // 4. 关联查询商品信息
//        orderItems.forEach(item -> {
//            ProductDTO productDTO = productService.getProductById(item.getProductId());
//
//        });

        // 3. 转换为DTO列表
//        return orderItems.stream().map(item -> {
//            OrderItemsDTO dto = new OrderItemsDTO();
//            // 使用BeanUtils复制属性
//            BeanUtils.copyProperties(item, dto);
//            return dto;
//        }).collect(Collectors.toList());
    }
}